package com.xingqing.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.xingqing.config.FileStorageConfig;
import com.xingqing.service.FileStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Service
@ConditionalOnProperty(name = "file.storage.type", havingValue = "oss")
public class OssFileStorageService implements FileStorageService {

    private final FileStorageConfig.Oss ossConfig;

    public OssFileStorageService(FileStorageConfig fileStorageConfig) {
        this.ossConfig = fileStorageConfig.getOss();
    }

    @Override
    public String upload(MultipartFile file, String fileType) throws Exception {
        // 获取原始文件名和扩展名
        String originalFilename = file.getOriginalFilename();
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        // 生成新的文件名
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String fileName = fileType + "_" + UUID.randomUUID().toString().replace("-", "") + "_" + timestamp + extension;

        // 构建OSS对象键（文件路径）
        String objectKey = ossConfig.getPathPrefix() + fileType + "/" + fileName;

        // 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(
                ossConfig.getEndpoint(),
                ossConfig.getAccessKeyId(),
                ossConfig.getAccessKeySecret()
        );

        try {
            // 上传文件到OSS
            InputStream inputStream = file.getInputStream();
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    ossConfig.getBucketName(),
                    objectKey,
                    inputStream
            );

            ossClient.putObject(putObjectRequest);
            log.info("文件上传到OSS成功，对象键: {}", objectKey);

            // 生成访问URL
            String fileUrl;
            if (ossConfig.getUrlPrefix() != null && !ossConfig.getUrlPrefix().trim().isEmpty()) {
                // 使用配置的URL前缀
                fileUrl = ossConfig.getUrlPrefix() + "/" + objectKey;
            } else {
                // 自动生成URL前缀
                String bucketDomain = "https://" + ossConfig.getBucketName() + "." + 
                                    ossConfig.getEndpoint().replace("https://", "").replace("http://", "");
                fileUrl = bucketDomain + "/" + objectKey;
            }
            
            log.info("OSS文件访问URL: {}", fileUrl);
            return fileUrl;

        } finally {
            // 关闭OSS客户端
            ossClient.shutdown();
        }
    }

    @Override
    public void delete(String fileUrl) throws Exception {
        if (fileUrl == null || !fileUrl.contains(ossConfig.getBucketName())) {
            log.warn("无效的OSS文件URL: {}", fileUrl);
            return;
        }

        // 从URL中提取对象键
        String objectKey;
        if (ossConfig.getUrlPrefix() != null && !ossConfig.getUrlPrefix().trim().isEmpty() 
            && fileUrl.startsWith(ossConfig.getUrlPrefix())) {
            // 使用配置的URL前缀解析
            objectKey = fileUrl.substring(ossConfig.getUrlPrefix().length() + 1);
        } else {
            // 自动解析对象键
            String bucketDomain = "https://" + ossConfig.getBucketName() + "." + 
                                ossConfig.getEndpoint().replace("https://", "").replace("http://", "");
            if (fileUrl.startsWith(bucketDomain)) {
                objectKey = fileUrl.substring(bucketDomain.length() + 1);
            } else {
                log.warn("无法解析OSS文件URL: {}", fileUrl);
                return;
            }
        }

        // 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(
                ossConfig.getEndpoint(),
                ossConfig.getAccessKeyId(),
                ossConfig.getAccessKeySecret()
        );

        try {
            // 删除OSS对象
            ossClient.deleteObject(ossConfig.getBucketName(), objectKey);
            log.info("OSS文件删除成功，对象键: {}", objectKey);

        } finally {
            // 关闭OSS客户端
            ossClient.shutdown();
        }
    }
}